#!/usr/local/env python
# -*- coding: utf-8 -*-
import os
from six.moves import configparser as ConfigParser
from agent520 import constants
import logging


class INI_Parser(object):
    """
    INI parser class
    """
    def __init__(self, config_file=None):
        if config_file is None:
            self.config_file = constants.ini_files
        self.default_config = {
            "max_data_span": 60,
            "max_data_age": 60 * 10,
            "logging_level": logging.info,
            "threads": 100,
            "ttl": 60,
            "interval": 60,
            "plugins": os.path.join(constants.__FILEABSDIRNAME__, "plugins"),
            "enabled": "no",
            "subprocess": "no",
            "user": "",
            "server": "",
            "api_host": "ingest.monitoring520.io",
            "hello_api_host": "api.monitoring520.io",
            "api_path": "/v2/server/poll",
            "log_file": "/var/log/agent520.log",
            "log_file_mode": "a",
            "max_cached_collections": 10,
        }
        self.sections = ["agent", "execution", "data"]
        self.config = ConfigParser.RawConfigParser(self.default_config)
        self._config_init()
        self.config.read(self.config_file)

    def _config_init(self):
        """
        Initialize configuration object
        """
        for section in self.sections:
            self._config_section_create(section)
            if section == "data":
                self.config.set(section, "interval", 1)
            if section == "agent":
                self.config.set(section, "interval", 0.5)

    def get(self, section, key):
        return self.config.get(section, key)

    def getint(self, section, key):
        return self.config.getint(section, key)

    def getboolean(self, section, key):
        return self.config.getboolean(section, key)

    def getfloat(self, section, key):
        return self.config.getfloat(section, key)

    def getlist(self, section, key):
        return self.config.get(section, key).split(",")

    def getdict(self, section):
        return dict(self.config.items(section))

    def set(self, section, key, value):
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, key, value)

    def write(self, buf):
        self.config.write(buf)

    def save(self):
        with open(self.config_file, "w") as configfile:
            self.config.write(configfile)

    def _config_section_create(self, section):
        if not self.config.has_section(section):
            self.config.add_section(section)


config = INI_Parser()
